<template>
  <el-dialog :close-on-click-modal="false" top="5vh" v-model="show" :title="isInfo ? '详细信息' : isEdit ? '编辑' : '新建'"
    @close="close">
    <div class="content flex-y-c" style="width: 100%">
      <div class="step_box" v-if="!isInfo">
        <el-steps style="max-width: 100%" :active="stepActive" align-center>
          <el-step title="产品基础信息" :description="isEdit ? '编辑产品' : '创建产品'" />
          <el-step title="输入产品链接信息" description="输入详细的内容" />
        </el-steps>
      </div>

      <div class="step_content">
        <div class="content_box" v-show="stepActive == 1">
          <h4 class="mb-10">产品基础信息</h4>
          <el-form ref="ruleFormRef" style="width: 100%" :model="ruleForm" :rules="rules" label-width="auto"
            class="box_form" status-icon>
            <el-form-item label="产品" prop="productCode">
              <el-select :disabled="isInfo || isEdit" v-model="ruleForm.productCode" placeholder="请选择产品" filterable
                style="width: 100%">
                <el-option :value="item.key" style="width: 100%" v-for="item in listCollect.productList"
                  :label="item.value" :key="item.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="运营商" prop="isp">
              <el-select v-model="ruleForm.isp" placeholder="请选择运营商">
                <el-option :disabled="isInfo" v-for="item in ispSelectList" :key="item.id" :label="item.value"
                  :value="item.key" />
              </el-select>
            </el-form-item>
            <el-form-item label="白名单省" prop="whiteListProvince">
              <el-select :disabled="isInfo" v-model="ruleForm.whiteListProvince" @change="proChange"
                placeholder="请选择所在省份">
                <el-option v-for="item in province" :key="item.id" :label="item.dictItemName"
                  :value="item.dictItemCode" />
              </el-select>
            </el-form-item>
            <el-form-item label="白名单市" prop="whiteListCity">
              <el-select :disabled="isInfo" v-model="ruleForm.whiteListCity" @change="proChange1" placeholder="请选择所在市">
                <el-option v-for="item in selectProvinceCity" :key="item.id" :label="item.dictItemName"
                  :value="item.dictItemCode" />
              </el-select>
            </el-form-item>
            <el-form-item label="限制单量" prop="orderTotalQuota">
              <el-input :disabled="isInfo" v-model.number="ruleForm.orderTotalQuota" placeholder="请输入" />
            </el-form-item>
          </el-form>
        </div>
        <div class="content_box1" v-show="stepActive == 2">
          <el-form style="max-width: 600px" :model="dynamicValidateForm" :rules="rules" ref="recommendRef"
            label-width="auto" class="demo-ruleForm" status-icon>
            <div v-for="(domain, index) in dynamicValidateForm.domains" :key="index" class="box_item">
              <div class="clear">
                <el-button type="primary" size="small" color="#467eff" @click="handRecommend(1, domain, index)"
                  v-if="domain.btn">编辑</el-button>
                <el-button type="primary" size="small" color="#467eff" @click="handRecommend(2, domain, index)"
                  v-else>保存</el-button>
                <el-button type="danger" size="small" @click="removeDomain(domain)"
                  v-if="dynamicValidateForm.domains.length > 1">删除</el-button>
              </div>
              <el-form-item label="推荐产品" :prop="'domains.' + index + '.relationProductCode'" :rules="{
                required: true,
                message: '请选择推荐产品',
                trigger: 'blur'
              }">
                <el-select :disabled="domain.disabled" v-model="domain.relationProductCode" placeholder="请选择产品"
                  style="width: 100%">
                  <el-option :value="item.key" style="width: 100%" v-for="item in listCollect.productList"
                    :label="item.value" :key="item.id"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="推荐产品概率" :prop="'domains.' + index + '.relationProductRate'" :rules="{
                required: true,
                message: '请填写产品概率',
                trigger: 'blur'
              }">
                <el-input v-model.number="domain.relationProductRate" :disabled="domain.disabled" />
              </el-form-item>
              <el-form-item label="推荐产品链接" :prop="'domains.' + index + '.relationProductUri'" :rules="{
                required: true,
                message: '请填写链接',
                trigger: 'blur'
              }">
                <el-input v-model="domain.relationProductUri" :disabled="domain.disabled" placeholder="请输入推荐产品链接" />
              </el-form-item>
            </div>
          </el-form>
          <div class="ben_box flex-x-c">
            <el-button :disabled="addbtnStatus" type="primary" class="btn" @click="addDomain">
              + 加产品</el-button>
          </div>
        </div>

        <div class="content_box1" v-if="isInfo == true">
          <h4 class="mb-10" v-if="dynamicValidateForm.domains.length">
            推荐产品信息
          </h4>
          <el-form v-if="dynamicValidateForm.domains.length" style="width: 100%" :model="dynamicValidateForm"
            :rules="rules" ref="recommendRef" label-width="auto" class="demo-ruleForm" status-icon>
            <div v-for="(domain, index) in dynamicValidateForm.domains" :key="index" class="box_item">
              <el-form-item label="推荐产品" :prop="'domains.' + index + '.relationProductCode'" :rules="{
                required: true,
                message: '请选择推荐产品',
                trigger: 'blur'
              }">
                <el-select :disabled="domain.disabled" v-model="domain.relationProductCode" placeholder="请选择产品"
                  style="width: 100%">
                  <el-option :value="item.key" style="width: 100%" v-for="item in listCollect.productList"
                    :label="item.value" :key="item.id"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="推荐产品概率" :prop="'domains.' + index + '.relationProductRate'" :rules="{
                required: true,
                message: '请填写产品概率',
                trigger: 'blur'
              }">
                <el-input v-model="domain.relationProductRate" :disabled="true" />
              </el-form-item>
              <el-form-item label="推荐产品链接" :prop="'domains.' + index + '.relationProductUri'" :rules="{
                required: true,
                message: '请填写链接',
                trigger: 'blur'
              }">
                <el-input v-model="domain.relationProductUri" :disabled="domain.disabled" placeholder="请输入推荐产品链接" />
              </el-form-item>
            </div>
          </el-form>
        </div>

        <!-- <div class="content_box flex-x-c" v-show="stepActive == 3" style="height: 280px">
          <div class="flex-y-c">
            <el-icon :size="40">
              <SuccessFilled color="#467eff" />
            </el-icon>
            <h2 class="mt-20">
              {{ isEdit ? "编辑成功" : "创建成功" }}
            </h2>
          </div>
        </div> -->
      </div>
    </div>
    <template #footer>
      <span class="dialog-footer flex-x-c" v-if="!isInfo">
        <!-- v-if="stepActive == 2" -->
        <el-button @click="last" v-if="stepActive == 2"> 上一步 </el-button>
        <el-button type="primary" @click="basicsSubmit(ruleFormRef)" color="#467eff" v-if="stepActive == 1">
          下一步
        </el-button>
        <el-button type="primary" @click="basicsSubmit(ruleFormRef)" color="#467eff" v-if="stepActive == 2">
          关闭
        </el-button>
      </span>
      <span v-if="isInfo">
        <el-button @click="tableFlush"> 关闭 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import {
  addproductCnf,
  addproductCnfUrl,
  deleteRelation
} from "@/api/product"
import { ElMessage } from "element-plus"
import { ref, reactive, nextTick } from "vue"
import { useColorStore } from "@/store/common"
import { storeToRefs } from "pinia"
import { useComListData } from "@/store/list"

const { listCollect } = useComListData()

const provinceData = useColorStore()
const { province, selectProvinceCity } = storeToRefs(provinceData)
const { filterData } = provinceData
interface Iprops {
  infoData: any
}

const props = defineProps<Iprops>()
const emit = defineEmits(["tableFlush", 'searchEdit'])
let show = ref(false)
let boxShow = ref(false)
const flag = ref(0) // 计数
let stepActive = ref(1)
let editStepId = ref("")
let addbtnStatus = ref(true)
let recommendRef = ref()
let isEdit = ref(false)
let ruleFormRef = ref()

const isInfo = ref(false)
const ruleForm = reactive<any>({
  productCode: "", // 产品编码
  isp: "", // 运营商
  whiteListProvince: "", // 白名单省
  whiteListCity: "", // 白名单市
  orderTotalQuota: ""
})
const addOrEdit = ref()
const tableFlush = () => {
  selectProvinceCity.value = null
  show.value = false
  if (addOrEdit.value == 'add') {
    emit("tableFlush")

  } else {
    emit('searchEdit')
  }
}

const ispSelectList = ref([
  { key: "ChinaMobile", value: "中国移动", id: 1 },
  { key: "ChinaUnicom", value: "中国联通", id: 2 },
  { key: "ChinaTelecom", value: "中国电信", id: 3 },
  { key: "ChinaBroadnet", value: "中国广电", id: 4 },
  { key: "Other", value: "其他", id: 5 }
])
const dynamicValidateForm = reactive<any>({
  domains: [
    {
      // productCode:'aaa',
      disabled: false,
      btn: false,
      relationProductUri: "",
      relationProductCode: "", //  推荐产品编码
      relationProductRate: 0 // 概率
    }
    // {
    //   // productCode:'aaa',
    //   disabled: false,
    //   btn:false,
    //   relationProductUri: "",
    //   relationProductCode: "", //  推荐产品编码
    //   relationProductRate: 20 // 概率
    // }
  ]
})

watch(
  () => props.infoData,
  async () => {
    await nextTick()
    addbtnStatus.value = false
    stepActive.value = 1
    proChange(props.infoData.whiteListProvince)
    for (let key in props.infoData) {
      if (props.infoData.hasOwnProperty(key)) {
        if (ruleForm.hasOwnProperty(key)) {
          ruleForm[key] = props.infoData[key]
        }
      }
      if (props.infoData.recommendationRelationList.length !== 0) {
        boxShow.value = true
        if (isInfo) {
          dynamicValidateForm.domains =
            props.infoData.recommendationRelationList.map((item: any) => {
              item.disabled = true
              item.btn = true
              return item
            })
        } else {
          dynamicValidateForm.domains =
            props.infoData.recommendationRelationList.map((item: any) => {
              item.disabled = false
              item.btn = false
              return item
            })
        }
      }
    }

    // 编辑标识 ID
    editStepId.value = props.infoData.id
  }
)

const proChange = (val: any) => {
  province.value.some((item: any) => {
    if (val == item.dictItemCode) {
      filterData(1, item.id, item.dictItemCode)
      ruleForm.whiteListCity = null
    }
  })
}

const proChange1 = (val: any) => {
  selectProvinceCity.value.some((item: any) => {
    if (val == item.dictItemCode) {
      return
    }
  })
}

/*推荐产品*/
const removeDomain = async (item: any) => {
  if (dynamicValidateForm.domains.length == 1) return

  if (item.id) {
    deleteRelation({ id: item.id }).then((res) => {
      if (res.code == 20000) {
        ElMessage.success("删除成功")
        const index = dynamicValidateForm.domains.indexOf(item)
        if (index !== -1) {
          dynamicValidateForm.domains.splice(index, 1)
          flag.value--
        }
      }
    })
  } else {
    const index = dynamicValidateForm.domains.indexOf(item)
    if (index !== -1) {
      dynamicValidateForm.domains.splice(index, 1)
      addbtnStatus.value = false

      flag.value--
    }
  }
}

const addDomain = () => {
  if (dynamicValidateForm.domains.length == 5) {
    ElMessage.warning("最多推荐五条产品")
    return
  }
  dynamicValidateForm.domains.push({
    // key: Date.now(),
    disabled: false,
    btn: false,
    relationProductUri: "",
    relationProductCode: "", //  推荐产品编码
    relationProductRate: "" // 概率
  })
  addbtnStatus.value = true
}
const handValidate = () => {
  return new Promise((resolve, reject) => {
    recommendRef.value?.validate((valid: any) => {
      if (valid) {
        resolve(true)
      } else {
        reject(false)
      }
    })
  })
}
const handRecommend = async (code: number, _: any, index: number) => {
  if (code == 1) {
    dynamicValidateForm.domains[index].disabled =
      !dynamicValidateForm.domains[index].disabled
    dynamicValidateForm.domains[index].btn =
      !dynamicValidateForm.domains[index].btn
  } else {
    // 保存时候跟新上一次产品概率
    let sta = await handValidate()
    if (!sta) return
    // 保存走修改
    let params: any = {
      productCode: ruleForm.productCode,
      // productCode: '1123',
      ...dynamicValidateForm.domains[index]
    }
    delete params.disabled
    delete params.btn

    let res = await addproductCnfUrl(params)
    if (res.code == 20000) {
      dynamicValidateForm.domains[index].btn =
        !dynamicValidateForm.domains[index].btn
      dynamicValidateForm.domains[index].disabled = true
      dynamicValidateForm.domains[index]["id"] = res.data
      addbtnStatus.value = false
      ElMessage.success("操作成功")
    }
  }
}

const last = () => {
  if (stepActive.value == 1) return
  stepActive.value--
}

const rules = reactive({
  productCode: [{ required: true, message: "请选择产品", trigger: "blur" }],
  isp: [{ required: true, message: "请选择运营商", trigger: "blur" }],
  whiteListProvince: [
    { required: true, message: "请选择省份", trigger: "blur" }
  ],
  whiteListCity: [{ required: true, message: "请选择市", trigger: "blur" }],
  orderTotalQuota: [
    { required: true, message: "请填写限制单量", trigger: "blur" }
  ]
})

const basicsSubmit = async (formEl: any) => {
  // editStepId
  if (stepActive.value == 1) {
    if (!formEl) return
    await formEl?.validate((valid: any) => {
      if (valid) {
        let obj: any = { ...ruleForm }
        if (editStepId.value && editStepId.value !== "") {
          obj["id"] = editStepId.value
        }
        addproductCnf(obj).then((res) => {
          if (res.code == 20000) {
            boxShow.value = true
            editStepId.value = res.data
            ElMessage.success("操作成功")
            isEdit.value = true
            if (stepActive.value++ > 2) stepActive.value = 1
          }
        })
      }
    })
  } else if (stepActive.value == 2) {
    await recommendRef.value.validate((valid: any) => {
      if (valid) {
        stepActive.value++
        tableFlush()
      } else {
      }
    })
  }
}



const handShow = (t: any, code?: number) => {
  show.value = true
  if (code == 2) {
    isEdit.value = true
    addOrEdit.value = 'edit'
  } else {
    addOrEdit.value = 'add'
    isInfo.value = t
  }
}
const close = () => {
  ruleFormRef.value?.resetFields()
  isInfo.value = false
  boxShow.value = false
  editStepId.value = ""
  isEdit.value = false
  stepActive.value = 1

  dynamicValidateForm.domains = [
    {
      // productCode:'',
      relationProductUri: "",
      relationProductCode: "", //  推荐产品编码
      relationProductRate: "" // 概率
    }
  ]
}
defineExpose({
  handShow
})
</script>

<style lang="scss" scope>
.content_box1 {
  max-height: 300px;
  overflow: auto;
}

.content {
  box-sizing: border-box;
  padding: 10px 30px 30px 30px;

  .step_box {
    width: 100%;
    margin-bottom: 20px;
  }

  .step_content {
    min-height: 280px;
    width: 80%;

    // background-color: skyblue;
    .box_item {
      .clear {
        width: 100%;
        display: flex;
        justify-content: flex-end;
        margin: 10px 0;

        .icon {
          &:hover {
            color: #1f63ff;
          }
        }
      }
    }

    .title {
      margin: 10px 0 15px 0;
      color: #0c0c0c;
      font-size: 16px;
    }

    .box_form {
      box-sizing: border-box;
      // padding: 0 20px
    }

    .ben_box {
      width: 100%;

      .btn {
        width: 50% !important;
      }
    }
  }

  .sco {
    overflow-y: auto;
    height: 400px;
  }

  .sco::-webkit-scrollbar {
    display: none;
  }

  .box {
    padding-bottom: 10px;
  }
}
</style>
